<template>
  <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
    <template #default>
      <n-form ref="formRef" :model="model" :rules="rules" style="padding-top: 20px">
        <n-form-item path="title" label="课程名称">
          <n-input v-model:value="model.title" />
        </n-form-item>
        <n-form-item path="difficultyLevel" label="难易等级">
          <n-radio-group v-model:value="model.difficultyLevel">
            <n-space>
              <n-radio
                v-for="item in difficultyLevelOptions"
                :key="item.dictValue"
                :value="item.dictValue"
              >
                {{ item.dictLabel }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item path="classify" label="一级分类">
          <n-radio-group v-model:value="model.classify" :on-update:value="classifyUpdate">
            <n-space item-style="display: flex;">
              <n-radio
                v-for="item in classifyOptions"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictLabel"
              />
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item path="courseType" label="二级分类">
          <n-checkbox-group v-model:value="model.courseType">
            <n-space item-style="display: flex;">
              <n-checkbox
                v-for="item in courseTypeOptions"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictLabel"
              />
            </n-space>
          </n-checkbox-group>
        </n-form-item>
        <n-form-item path="status" label="是否上架">
          <n-select
            v-model:value="model.status"
            label-field="dictLabel"
            value-field="dictValue"
            :options="statusOptions"
          />
        </n-form-item>
        <n-form-item path="isFree" label="是否免费">
          <n-switch
            :checked-value="0"
            :unchecked-value="1"
            v-model:value="model.isFree"
            :on-update:value="isFreeUpdate"
          />
        </n-form-item>
        <n-form-item path="price" label="课程价格">
          <n-input-number
            v-model:value="model.price"
            :show-button="false"
            :disabled="model.isFree === 0"
            :precision="2"
          >
            <template #suffix> 元 </template>
          </n-input-number>
        </n-form-item>
        <n-form-item path="coverUrl" label="课程封面">
          <BasicUpload
            :action="`${apiUrl}/system/oss/upload`"
            :headers="uploadHeaders"
            :max-number="1"
            name="file"
            @upload-change="coverUploadChange"
            v-model:value="uploadList"
            helpText="文件不超过20MB"
          />
        </n-form-item>
        <n-form-item path="description" label="课程描述">
          <n-input v-model:value="model.description" type="textarea" maxlength="100" show-count />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script setup lang="ts">
  import { basicModal, useModal } from '@/components/Modal';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStore } from '@/store/modules/user';
  import { defineEmits, reactive, ref, watch } from 'vue';
  import { FormRules, useMessage } from 'naive-ui';
  import { saveCourseApi, updateCourseApi } from '@/api/course';
  import { getDictApi } from '@/api/common';

  const props = defineProps({
    currentRow: {
      type: Object,
      default: () => null,
    },
  });

  const emit = defineEmits(['finish']);

  const { apiUrl } = useGlobSetting();
  const userStore = useUserStore();
  const token = userStore.getToken;

  interface ModelType {
    title: string | null;
    difficultyLevel: number | null;
    classify: number | null;
    courseType: Array<any>;
    description: string | null;
    coverUrl: string;
    status: number | null;
    isFree: number | null;
    price: number;
  }

  const model = ref<ModelType>({
    title: null,
    difficultyLevel: 0,
    classify: 0,
    courseType: [],
    description: null,
    coverUrl: '',
    status: 0,
    isFree: 0,
    price: 0,
  });

  const rules: FormRules = {
    title: [
      {
        required: true,
        message: '请输入课程名称',
      },
    ],
    difficultyLevel: [
      {
        required: true,
        message: '请选择难易等级',
      },
    ],
    classify: [
      {
        required: true,
        message: '请选择一级分类',
      },
    ],
    courseType: [
      {
        required: true,
        message: '请选择二级分类',
      },
    ],
    status: [
      {
        required: true,
        message: '请选择是否上架',
      },
    ],
    price: [
      {
        required: true,
        message: '请输入价格',
      },
    ],
  };

  const dictMapping = {
    0: 'major_type',
    1: 'skill_type',
    2: 'empowerment_type',
    3: 'guide_type',
    4: 'case_type',
    5: 'tool_type',
  };

  const difficultyLevelOptions = ref<any[]>([]);
  const classifyOptions = ref<any[]>([]);
  const courseTypeOptions = ref<any[]>([]);
  const statusOptions = ref<any[]>([]);

  const uploadList = ref<any[]>([]);
  const uploadHeaders = reactive({
    Authorization: token,
  });

  const formRef = ref();
  const modalRef: any = ref(null);
  const message = useMessage();

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '课程',
  });

  async function okModal() {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        let params: any = {
          ...model.value,
          courseType: model.value.courseType.join(','),
        };
        try {
          if (params.courseId) {
            await updateCourseApi(params);
            message.success('修改成功');
          } else {
            await saveCourseApi(params);
            message.success('新增成功');
          }
          message.destroyAll();
          emit('finish', model.value);
        } finally {
          setSubLoading(false);
          closeModal();
        }
      } else {
        console.log(errors);
        setSubLoading(false);
      }
    });
  }

  async function getClassifyDict() {
    const data: any = await getDictApi('course_classify');
    classifyOptions.value = data || [];
  }

  getClassifyDict();

  function classifyUpdate(value: any) {
    model.value.classify = value;
    model.value.courseType = [];
    getCourseTypeDict(value);
  }

  async function getCourseTypeDict(classifyType: any) {
    let courseType = dictMapping[classifyType];
    const data: any = await getDictApi(courseType);
    courseTypeOptions.value = data || [];
  }

  async function getDifficultyLevelDict() {
    const data: any = await getDictApi('difficulty_level');
    difficultyLevelOptions.value = data || [];
  }

  getDifficultyLevelDict();

  async function getStatusOptionsDict() {
    const data: any = await getDictApi('yes_or_no');
    statusOptions.value = data || [];
  }

  getStatusOptionsDict();

  function isFreeUpdate(value: any) {
    model.value.isFree = value;
    if (value === 0) {
      model.value.price = 0;
    }
  }

  function coverUploadChange(list: any[]) {
    model.value['coverUrl'] = list.join(',');
  }

  watch(
    () => props.currentRow,
    (currentRow) => {
      if (currentRow?.courseId) {
        const row = JSON.parse(JSON.stringify(currentRow));
        model.value = Object.assign({}, row, {
          courseType: currentRow.courseType ? currentRow.courseType.split(',').map(Number) : [],
        });
        uploadList.value = model.value.coverUrl ? [model.value.coverUrl] : [];
      }

      getCourseTypeDict(model.value.classify);
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    openModal,
  });
</script>

<style scoped lang="less"></style>
